package yi.wuhenbot.Service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yi.wuhenbot.Controller.BotController;
import yi.wuhenbot.dao.FishingConfigMapper;
import yi.wuhenbot.entity.Fishing.FishingConfig;
import java.util.List;
import java.util.Random;

/**
 * @author wuhen
 */
@Service
public class FishingConfigService {
    @Autowired
    private FishingConfigMapper fishingConfigMapper;
    private static final Logger logger = LoggerFactory.getLogger(BotController.class);

    /**
     * 根据probability随机获取一条数据，probability越大概率越高，返回的是id
     * @return 钓点id
     */
    public int getFishingConfigByProbability() {
        // 获取全部数据
        List<FishingConfig> fishingConfigList = fishingConfigMapper.getAllProbabilityFishingConfig();
        if (fishingConfigList == null || fishingConfigList.isEmpty()) {
            // 或者抛出异常，或者返回一个默认值
            return -1;
        }

        // 计算总概率
        double totalProbability = 0;
        for (FishingConfig config : fishingConfigList) {
            totalProbability += config.getProbability();
        }

        // 生成一个随机数
        Random random = new Random();
        double randomValue = random.nextDouble() * totalProbability;

        // 根据随机数选择一条数据
        double cumulativeProbability = 0;
        for (FishingConfig config : fishingConfigList) {
            cumulativeProbability += config.getProbability();
            if (randomValue <= cumulativeProbability) {
                // 打印匹配的概率
                logger.info("匹配的概率: " + config.getProbability());
                // 打印匹配的id
                logger.info("匹配的id: " + config.getId());
                // 概率匹配成功，返回当前数据的id
                return config.getId();
            }
        }

        // 如果没有匹配的数据，返回列表中最后一个数据的id（理论上不应该发生）
        return fishingConfigList.get(fishingConfigList.size() - 1).getId();
    }

    /**
     * 根据id查询
     * @param id 钓点id
     * @return 钓点配置
     */
    public FishingConfig getFishingConfigById(int id) {
        return fishingConfigMapper.getFishingConfigById(id);
    }
}